package com.xsqf.jt808.netty.handler;

import com.xsqf.jt808.common.config.JT808Const;
import com.xsqf.jt808.common.vo.resp.PositionReply;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * PositionHandler
 *
 * @author
 * @date 2020/5/27 17:43
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class PositionHandler extends BaseHandler<PositionReply> {

    private ChannelHandlerContext ctx;
    private ChannelPromise promise;
    private PositionReply response;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.ctx = ctx;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PositionReply msg) throws Exception {

        if (msg != null && msg.getHeader().getMsgId() == JT808Const.TERNIMAL_RESP_LOCATION_) {
            log.info("位置信息查询：" + msg.toString());
            response = msg;
            promise.setSuccess();
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    public synchronized ChannelPromise sendMessage(Object message) {
        while (ctx == null) {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
                //logger.error("等待ChannelHandlerContext实例化");
            } catch (InterruptedException e) {
                log.error("等待ChannelHandlerContext实例化过程中出错", e);
            }
        }
        promise = ctx.newPromise();
        ctx.writeAndFlush(message);
        return promise;
    }

    public PositionReply getResponse() {
        return response;
    }

}
